package com.transcargo.action;

/**
 * Date: 17.02.2011
 * Time: 22:47:45
 */

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import com.transcargo.db.db;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.config.ConfigManager;


public class Action extends HttpServlet
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected ArrayList<String[]> list = null;
    protected Iterator<String[]> iter = null;
    protected Cookie[] cookies = null;
    protected db dbase = null;
    protected Cookie cookie = null;
    
	protected void sendRedirect(HttpServletResponse response, String addr) throws ServletException {
    	try {
			response.getWriter().println(RPCOutput.generate(addr));
		} catch (IOException e) {
			throw new ServletException("IOException: " + e.getMessage());
		}
	}
	protected void sendError(HttpServletResponse response, Exception e) throws ServletException {
    	try {
			response.getWriter().println(RPCOutput.generate(e));
		} catch (IOException ee) {
			throw new ServletException("IOException: " + ee.getMessage());
		}
	}
    protected void InitActionServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        dbase = new db();
        if (!dbase.init()) throw new ServletException("Failed to connect to DB: " + ConfigManager.getProperty("DB_URL"));
        cookies = request.getCookies();
        response.setCharacterEncoding("UTF-8");
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ServletException(e.getMessage());
        }
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    	try {
			PrintWriter out = response.getWriter();
			out.println("Request invokation error");
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        InitActionServlet(request, response);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "text/xml; charset=UTF-8");
        processAction(request, response);
    }
}
